package bqg

import (
	"fmt"
	"os"
	"save-kindle/log"
)

type Task[T string] interface {
	DoAction() T
}

type DoBatch[T string] struct {
	Tasks []Task[T]
	pool  chan struct{}
}

func (d *DoBatch[T]) DoAction() []T {
	counter := make(chan struct{})
	resultMap := make(map[int]T)
	resultList := make([]T, len(d.Tasks))

	go func() {
		for i := range d.Tasks {
			task := d.Tasks[i]
			d.pool <- struct{}{}
			go func(t Task[T], index int) {
				actionResult := t.DoAction()
				resultMap[index] = actionResult
				resultList[index] = actionResult
				<-d.pool
				counter <- struct{}{}
			}(task, i)
		}
	}()

	taskCount := len(d.Tasks)
	count := 0
	for count != taskCount {
		select {
		case <-counter:
			count++
		}
	}
	return resultList
}

type SplitFileTask struct {
	fileName  string
	index     int
	batchTask DoBatch[string]
}

func (sft SplitFileTask) a() {
	file, err := os.OpenFile(fmt.Sprintf("%s_%d.txt", sft.fileName, sft.index), os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		log.PrintErr(err.Error())
	}
	defer file.Close()

	actionResult := sft.batchTask.DoAction()

	for i := range actionResult {
		file.WriteString(actionResult[i])
	}
}

type FileHandler[T any] struct {
	AllTask []T
}

func (h *FileHandler[T]) DoHandler(fileName string) {
	step := 50
	length := len(h.AllTask)
	count := length / step
	if length%step != 0 {
		count++
	}

	for i := 0; i < count; i++ {
		task := SplitFileTask{fileName: fileName, index: i, batchTask: DoBatch[string]{
			Tasks: nil,
			pool:  make(chan struct{}, 5),
		}}

		task.a()
	}

	// 把文件合起来
}
